﻿using AutoMapper;
using TMOOC.CM.MobileShop.Entity;
using TMOOC.CM.MobileShop.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace TMOOC.CM.MobileShop.Business.Base_Manage
{
    public class HomeBusiness : BaseBusiness<Base_User>, IHomeBusiness, IDependency
    {




        public AjaxResult SubmitLogin(string userName, string password)
        {
            if ((userName.IsNullOrEmpty() || password.IsNullOrEmpty()))
                return Error("账号或密码不能为空！");
            password = password.ToMD5String();
            //允许使用手机号或者账号进行登入
            var theUser = GetIQueryable().Where(x => (x.UserName == userName||x.TelPhoneNo == userName) && x.Password == password).FirstOrDefault();
            if (theUser != null)
            {
                //生成token,有效期一天
                JWTPayload jWTPayload = new JWTPayload
                {
                    UserId = theUser.Id,
                    Expire = DateTime.Now.AddDays(1)
                };
                string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);

                return Success(token);
            }
            else
                return Error("账号或密码不正确！");
        }

        public AjaxResult ChangePwd(string oldPwd, string newPwd)
        {
            var theUser = Operator.Property;
            if (theUser.Password != oldPwd?.ToMD5String())
                return Error("原密码错误!");
            else
            {
                #region 执行密码更新
                //更新本地密码
                if (!ChangeLocalPwd(theUser, newPwd))
                    MLogHelper.Error("修改本地密码失败:新密码为" + newPwd, theUser.UserName);
                #endregion

                return Success();
            }
        }

        public AjaxResult RegistUser(string userName, string password, string telphoneNo,string realName)
        {
            if ((userName.IsNullOrEmpty() || password.IsNullOrEmpty()))
                return Error("账号或密码不能为空！");
            if (telphoneNo.IsNullOrEmpty())
                return Error("手机号不可为空");
            var theUser = GetIQueryable().Where(x => x.UserName == userName || x.TelPhoneNo == telphoneNo).FirstOrDefault();
            if (theUser != null)
                return Error("该手机号已注册。");
            Base_User bu = new Base_User
            {
                UserName = userName,
                Password = password.ToMD5String(),
                TelPhoneNo = telphoneNo,
                RealName= realName
            };
            bu.InitEntity();
            Insert(bu);
            return Success("注册成功");
        }


        #region 私有方法，更新密码
        /// <summary>
        /// 更新本地密码
        /// </summary>
        /// <param name="theUser"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        private bool ChangeLocalPwd(Base_User theUser, string newPwd)
        {
            try
            {
                theUser.Password = newPwd.ToMD5String();
                Update(Mapper.Map<Base_User>(theUser));
                return true;
            }
            catch (Exception ex)
            {
                MLogHelper.Error("修改本地密码失败"+ex.ToString() + ex.Message, "ChangePwd");
                return false;
            }
        }
        /// <summary>
        /// 更改U8密码
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <param name="u8APIURL"></param>
        /// <returns></returns>
        private bool ChangeU8Pwd(string userid, string oldpwd, string newpwd,string u8APIURL)
        {
            ////Dictionary<string, object> paramters = new Dictionary<string, object>();
            ////paramters.Add("uid", userid);
            ////paramters.Add("oldpwd", oldpwd);
            ////paramters.Add("newpwd", newpwd);
            userid = userid.Substring(2, userid.Length - 2);
            if (!StringHelper.IsNumberId(userid))
                return false;
            //{"userid":"","oldpassword":"","newpassword":""}
            var user = new
            {
                userid = userid,
                oldpassword=oldpwd,
                newpassword = newpwd
            };
            //issucess
            return Convert.ToBoolean(JObject.Parse(HttpHelper.PostData(u8APIURL,JsonConvert.SerializeObject(user)))["issucess"].ToString());
        }
        /// <summary>
        /// 更新邮箱密码
        /// </summary>
        /// <param name="userMail"></param>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <param name="mailAPIURL"></param>
        /// <returns></returns>
        private bool ChangeMailPwd(string userMail, string oldpwd, string newpwd, string mailAPIURL)
        {
            //Dictionary<string, object> paramters = new Dictionary<string, object>();
            //paramters.Add("mailAddress", userMail);
            //paramters.Add("mailPassword", newpwd);
            //	            { "mailAddress":"","mailPassword":""}

            var user = new
            {
                mailAddress = userMail,
                mailPassword = newpwd
            };
            //issucess
            return JObject.Parse(HttpHelper.PostData(mailAPIURL, JsonConvert.SerializeObject(user)))["errcode"].ToString() == "0"? true:false;
        }
        /// <summary>
        /// 更新AD密码
        /// </summary>
        /// <param name="_UserName"></param>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <param name="adApiURL"></param>
        /// <returns></returns>
        private bool ChangeADPwd(string _UserName, string oldpwd, string newpwd, string adApiURL)
        {
            var user = new {
                username = _UserName,
                userpassword = newpwd
            };
            var result = HttpHelper.PostData(adApiURL, JsonConvert.SerializeObject(user));
            var t1 = result.Substring(1, result.Length - 2).Replace("\\","");
            JObject jb = JObject.Parse(t1);
            var issuccess = jb["issuccess"].ToString();
            return Convert.ToBoolean(issuccess);
        }

       
        #endregion








    }
}
